/**
 * form 通用组件
 * */
layui.define(['xmSelect', 'form', 'laydate', 'formSelects', 'treeSelect', 'oss', 'laytpl', 'layedit'], (exports) => {
	let form = layui.form;
	let laydate = layui.laydate;
	let formSelects = layui.formSelects;
	let treeSelect = layui.treeSelect;
	let xmSelect = layui.xmSelect;
	let oss = layui.oss;
	let laytpl = layui.laytpl;
	let layedit = layui.layedit;
	
	let sdForm = {
		get(filter, verifys) {
		    let form_id = filter.indexOf('#') >= 0 ? filter : '#' + filter;
		    let postData = $(form_id).serializeArray();
		    let data = {};
		    $.each(postData, function () {
		        data[this.name] = this.value;
		    });
		    let result = {
		        check: true,
		        message: "",
		        data: data
		    }
		    // 校验
		    if(verifys){
		        $.each(verifys, function (index, filed) {
		            if ($.trim(data[filed]).length == 0) {
		                result.check = false;
		                result.message = $(form_id).find('input[name="' + filed + '"]').attr('placeholder');
		                $(form_id).find('input[name="' + filed + '"]').focus();
		                return false;
		            }
		        })
		    }
		
		    return result;
		},
		set(param) {
		    form.val(param.filter, param.data);
		    param.init ? param.init() : "";
		    form.render();
		},
		render(attrs) {
		    if(attrs){
		        $.each(attrs, function (i, item) {
		            form.render(item);
		        })
		    }else{
		        form.render();
		    }
		},
		date(params) {
		    $.each(params.id, function (i, id) {
		        id = '#' + id;
		        laydate.render({
		            elem: id,
		            format: params.format ? params.format : "yyyy-MM-dd",
		            theme: 'grid',
		            calendar: true
		        });
		    })
		},
		time(id, type, range, format){
		    id = id.indexOf('#') >= 0 ? id : '#' + id;
		    laydate.render({
		        elem: id,
		        type: type,
		        range: range || false,
		        format: format || null
		    });
		},
		submit(filter, fun) {
		    let f = 'submit(' + filter + ')';
		    form.on(f, function (obj) {
		        let field = obj.field;
		        fun ? fun(field) : "";
		    });
		},
		click(filter, fun) {
		    let f = 'submit(' + filter + ')';
		    form.on(f, function (obj) {
		        fun ? fun($(obj.elem)) : "";
		    });
		},
		switch(filter, fun) {
		    let f = 'switch(' + filter + ')';
		    form.on(f, function (obj) {
		        fun ? fun($(obj.elem)) : "";
		    });
		},
		upload: {
		    iv(path) {
		        $('.common-form-view').on('click', '.common-form-icon', function () {
		            let id = $(this).attr('id');
		            let fileId = '#input-' + id;
		            $(fileId).click();
		            $(fileId).unbind().change(function(){
		                oss.upload(id, 8, path);
		            })
		        })
		        $('.common-form-view').on('click', '.img-min-remove', function () {
		            $(this).parent().remove();
		        })
		
		    },
		    file(path){
		        $('.common-form-view').on('click', '.common-form-icon', function () {
		            let id = $(this).attr('id');
		            let fileId = '#input-' + id;
		            $(fileId).click();
		            $(fileId).unbind().change(function(){
		                oss.upload(id, 10, path);
		            })
		        })
		
		        $('.common-form-view').on('click', '.file-download', function () {
		            let url = $(this).attr('data-url');
		            window.location.href = url;
		        })
		    },
		    get(name, flag){
		        let items = [];
		        $('#layui-upload-' + name + '-list').find('.file-item').each(function () {
		            let src = $(this).attr('data-path');
		            items.push(src)
		        })
		        // flag == true 自动加网站前缀
		        if(flag){
		            let paths = [];
		            $.each(items, function (i, item) {
		                paths.push(config.resource + item);
		            })
		            return paths;
		        }else{
		            return items;
		        }
		    },
		    set(id, paths) {
		        oss.set(id, paths);
		    },
		    clean(name){
		        $('#layui-upload-' + name + '-list').empty();
		    }
		},
		edit: {
		    get(id) {
		        return layedit.getContent(id);
		    },
		    set(id, content) {
		        return layedit.setContent(id, content, false);
		    },
		    iv(id, isFull){
		        let tools1 = [
		            'undo',
		            'redo',
		            'code',
		            'strong',
		            'italic',
		            'underline',
		            'del',
		            'addhr',
		            '|',
		            'fontFomatt',
		            'fontfamily',
		            'fontSize',
		            'colorpicker',
		            'fontBackColor',
		            'face',
		            '|',
		            'left',
		            'center',
		            'right',
		            '|',
		            'link',
		            'unlink',
		            'images',//多图上传
		            'image_alt',//上传图片拓展
		            'attachment',//上传附件
		            'video', //视频上传
		            'anchors', //锚点
		            '|',
		            'table',//插入表格
		            'customlink',//插入自定义链接
		            'fullScreen'//全屏
		        ];
		        let tools2 = [
		            'undo',
		            'redo',
		            'code',
		            'strong',
		            'italic',
		            'underline',
		            'del',
		            'addhr',
		            '|',
		            'fontFomatt',
		            'fontfamily',
		            'fontSize',
		            '|',
		            'left',
		            'center',
		            'right'
		        ];
		        let editIndex = layedit.build('edit-' + id, {
		            uploadImage: {
		                accept: 'image',
		                acceptMime: 'image/*',
		                exts: 'jpg|png|gif|bmp|jpeg',
		                size: 1024 * 10,
		                done(data) {
		                    //console.log(data);
		                }
		            },
		            uploadVideo: {
		                accept: 'video',
		                acceptMime: 'video/*',
		                exts: 'mp4|flv|avi|rm|rmvb',
		                size: 1024 * 10 * 2,
		                done(data) {
		                    //console.log(data);
		                }
		            },
		            tool: isFull == true ? tools1 : tools2
		        });
		        return editIndex;
		    }
		},
		select(filter, fun){
		    let select = 'select(' + filter + ')'
		    form.on(select, function(obj){
		        fun ? fun($(obj.elem)) : "";
		    })
		},
		badge: {
		    get(name){
		        name = "tree-selected-" + name + "-view";
		        let id = name.indexOf('#') >= 0 ? name : '#' + name;
		        let badges = $(id).find('.layui-badge');
		        let arr = [];
		        if(badges.length > 0){
		            for(let i=0;i<badges.length;i++){
		                let element= $(badges[i]).get(0);
		                let dataId = $(element).attr('data-id');
		                arr.push(dataId)
		            }
		        }
		        return arr;
		    },
		    set(name, arr, attr){
		        name = "tree-selected-" + name + "-view";
		        let id = name.indexOf('#') >= 0 ? name : '#' + name;
		        let field = attr || "name";
		        arr.forEach(x => {
		            let html = "<span style=\"margin-right: 3px;margin-bottom: 2px;\" onclick=\"document.getElementById('badge-" + x.id + "').remove()\" id=\"badge-"+x.id+"\" class=\"layui-badge layui-bg-black\" data-id=\""+ x.id + "\">" + x[field] + "</span>";
		            $(id).append(html);
		        })
		    }
		},
		init: {
			form(form, data){
				let getTpl = tplForm.innerHTML;
				let view = document.getElementById('common-form-view');
				let formId = {};
				laytpl(getTpl).render(form, function(html){
				    view.innerHTML = html;
				    sdForm.render();
				
				    // 渲染日期 设值特殊组件值
				    let dateInputs = [];
				    $.each(form.items, function (i, item) {
				        let id = item.id ? item.id : item.name;
				
				        // 日期
				        if(item.code == 4){
				            // 判断type
				            if(item.type){
				                sdForm.time(id, item.type, item.range, item.format)
				            }else{
				                dateInputs.push(id);
				            }
				        }
				
				        // 下拉多选
				        if(item.code == 7){
				            // 渲染
				            let el = item.name || item.id;
				            let xm = xmSelect.render({
				                el: '#' + el, 
				                data: item.options
				            });
				            formId[el] = xm;
				        }
				
				        // 编辑器
				        if(item.code == 9){
				            let full = (typeof item.isFull) == 'undefined' ? true : item.isFull;
				            formId[item.name] = sdForm.edit.iv(id, full);
				        }
				
				        // 树形下拉选择器
				        if(item.code == 11){
				            // 渲染
				            treeSelect.render({
				                // 选择器
				                elem: '#tree-select-' + item.name,
				                // 数据
				                data: item.options,
				                // 单选/多选模式
				                type: item.type,
				                // 当多选模式 可用multi
				                multis: function(node){
				                    component.render.badge(node, item.name, item.prefix, item.len)
				                },
				                callback: item.callback,
				                prefix: (typeof item.prefix) == "undefined" ? 0 : item.prefix,
				                // 是否开启搜索功能：true/false，默认false
				                search: false,
				                // 一些可定制的样式
				                style: {
				                    folder: {
				                        enable: false
				                    },
				                    line: {
				                        enable: true
				                    }
				                },
				                // 点击回调
				                click: function(d){
				                    let current = d.current;
				                    item.callback ? item.callback(current) : '';
				                },
				                // 加载完成后的回调函数
				                success: function (d) {
				                    // 设置值
				                    if(data){
				                        treeSelect.checkNode(item.name, data[item.name]);
				                    }
				                }
				            });
				
				        }
				
				        // 自动完成
				        if(item.code == 12){
				            sdForm.autocomplete(
				                {id: item.id || item.name, //设置容器唯一id
				                cols: item.cols
				                , //设置表头
				                type: item.type || 'sug', //设置输入框提示类型：sug-下拉框，sugTable-下拉表格
				                url: item.url
				            })
				        }
				
				    })
				    if(dateInputs.length > 0){
				        sdForm.date({id: dateInputs})
				    }
				    // 设值
				    if(data){
				        sdForm.set({
				            filter: form.id,
				            data: data
				        })
				
				    }
				
				});
				return formId;
			},
			badge(node, name, prefix, len) {
			        let tem = [];
			        let id = '#tree-selected-' + name + '-view';
			        let check = (node.id).substring(0, 3);
			
			        if((typeof prefix) != "undefined"){
			            if(prefix == check){
			                tem.push(node);
			            }else{
			                let children = node.children;
			                try{
			                    if(children.length > 0){
			                        children.forEach(x => {
			                            let xid = (x.id).substring(0, 3);
			                            if(xid == prefix){
			                                tem.push(x);
			                            }
			                        })
			                    }
			                }catch (e) {
			
			                }
			            }
			        }else{
			            tem.push(node);
			        }
			
			
			        if(tem.length > 0){
			            let badges = $(id).find('.layui-badge');
			            let deleteIds = [];
			            tem.forEach(x => {
			                let optView = null;
			                if(badges.length > 0){
			                    for(let i=0;i<badges.length;i++){
			                        let element= $(badges[i]).get(0);
			                        let dataId = $(element).attr('data-id');
			
			                        if(dataId == x.id){
			                            optView = badges[i];
			                            deleteIds.push(dataId)
			                            optView.remove();
			                        }
			                    }
			                }
			            })
			
			            if((typeof len) != "undefined"){
			                badges = $(id).find('.layui-badge');
			                let thisLen = tem.length;
			                let oldLen = badges.length;
			                if((oldLen + thisLen) > len){
			                    component.tips.warning("当前多只能选择[" + len + "]条数据")
			                    return false;
			                }
			            }
			
			            tem.forEach(x => {
			                let check = false;
			                if(deleteIds.length > 0){
			                    deleteIds.forEach(y => {
			                        if(x.id == y){
			                            check = true;
			                        }
			                    })
			                }
			                if(!check){
			                    let html = "<span style=\"margin-right: 3px;margin-bottom: 2px;\" onclick=\"document.getElementById('badge-" + x.id + "').remove()\" id=\"badge-"+x.id+"\" class=\"layui-badge layui-bg-black\" data-id=\""+ x.id + "\">" + x.name + "</span>";
			                    $(id).append(html);
			                }
			            })
			        }
			    }
		}
	}
	
	exports('sdForm', sdForm);
})
